package com.ruoyi.medication.task;

import com.ruoyi.medication.domain.Medication;
import com.ruoyi.medication.domain.MedicationStock;
import com.ruoyi.medication.mapper.MedicationMapper;
import com.ruoyi.medication.mapper.MedicationStockMapper;
import com.ruoyi.medication.service.IMedicationStockService;
import com.ruoyi.system.domain.SysNotice;
import com.ruoyi.system.service.ISysNoticeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * 药品库存过期检查定时任务
 */
@Component
public class MedicationStockExpirationTask {
  private static final Logger log = LoggerFactory.getLogger(MedicationStockExpirationTask.class);

  // 库存预警阈值
  private static final long STOCK_WARNING_THRESHOLD = 100;

  @Autowired
  private MedicationMapper medicationMapper;

  @Autowired
  private ISysNoticeService noticeService;

  @Autowired
  private IMedicationStockService medicationStockService;

  @Autowired
  private MedicationStockMapper medicationStockMapper;
  /**
   * 每天中午12点执行过期检查
   */
  @Scheduled(fixedRate = 60000)
//  @Scheduled(cron = "0 0 12 * * ?")
  public void checkExpiration() {
    log.info("开始执行药品库存过期检查任务");
    try {
      // 查询所有未过期的药品库存
      List<MedicationStock> stocks = medicationStockService.selectValidStocks();

      Date now = new Date();
      int expiredCount = 0;

      for (MedicationStock stock : stocks) {
        if (stock.getExpirationDate() != null && stock.getExpirationDate().before(now)) {
          // 更新为过期状态
          stock.setStatus("2"); // 2表示过期状态
          Medication medication = medicationMapper.selectMedicationById(stock.getMedicationId());
          medication.setStock(medication.getStock() - stock.getQuantity());
          medicationMapper.updateMedication(medication);
          stock.setQuantity(new Long(0));
          medicationStockMapper.updateMedicationStock(stock);
          expiredCount += stock.getQuantity();
        }
      }

      log.info("药品库存过期检查完成，发现{}个过期药品,已移除药品", expiredCount);
    } catch (Exception e) {
      log.error("药品库存过期检查任务执行失败", e);
    }
  }

  /**
   * 每十分钟执行一次库存检查
   */
//  @Scheduled(cron = "0 0 12 * * ?")
  @Scheduled(fixedRate = 60000)
  public void checkStockWarning() {
    log.info("开始执行药品库存预警检查任务");
    try {
      // 查询所有药品
      List<Medication> medications = medicationMapper.selectMedicationList(new Medication());

      int warningCount = 0;
      String content = "";
      for (Medication medication : medications) {
        if (medication.getStock() < STOCK_WARNING_THRESHOLD) {
          // 创建警告通知
          content += String.format("药品【%s】当前库存为%d，低于预警阈值%d，请及时补充库存。",
                  medication.getName(), medication.getStock(), STOCK_WARNING_THRESHOLD) + "\n";
          warningCount++;
        }
      }
      if (warningCount > 0) {
        SysNotice notice = new SysNotice();
        notice.setNoticeTitle("药品库存预警");
        List<SysNotice> list = noticeService.selectNoticeList(notice);
        for (SysNotice sysNotice : list) {
          noticeService.deleteNoticeById(sysNotice.getNoticeId());
        }
        notice.setNoticeType("2"); // 2表示预警通知
        notice.setNoticeContent(content);
        notice.setStatus("0"); // 0表示正常
        notice.setCreateBy("1");

        // 保存通知
        noticeService.insertNotice(notice);
      }

      log.info("药品库存预警检查完成，发现{}个药品库存不足", warningCount);
    } catch (Exception e) {
      log.error("药品库存预警检查任务执行失败", e);
    }
  }
}